var express = require('express');

var fs = require('fs')

var path = require('path')

var userRouter = express.Router();

// 注册接口
userRouter.post('/register', (req, res) => {

    var { phone } = req.body;

    var filepath = path.join(__dirname, '../json/users.json')
    var arr = fs.readFileSync(filepath);
    arr = arr.toString() ? JSON.parse(arr) : []

    var a = arr.findIndex((item) => {
        return item.phone == phone;
    });


    if (a != -1) {
        res.send({ code: 400, msg: '该手机号已被注册,请重试!' })
    } else {
        arr.push({ ...req.body })
        fs.writeFileSync(filepath, JSON.stringify(arr), 'utf-8');
        res.send({ code: 200, msg: '注册成功!' })
    }
})



// 登录接口
userRouter.post('/login', (req, res) => {
    var { phone, pass } = req.body;

    var filepath = path.join(__dirname, '../json/users.json')
    var arr = fs.readFileSync(filepath);
    arr = arr.toString() ? JSON.parse(arr) : []


    var a = arr.findIndex((item, index) => {
        return item.phone == phone && item.pass == pass;
    })

    if (a != -1) {
        res.send({ code: 200, msg: '登陆成功!' })
    } else {
        res.send({ code: 400, msg: '登陆失败!' })
    }
})


// 查询
userRouter.get('/list', (req, res) => {

    var { page, count } = req.query;

    var filepath = path.join(__dirname, '../json/goods.json');
    var arr = fs.readFileSync(filepath);
    arr = arr.toString() ? JSON.parse(arr) : []


    var newarr = arr.slice((page - 1) * count, page * count)

    res.send({ code: 200, msg: '请求成功!', list: newarr })
})


//搜索接口
userRouter.get('/search', (req, res) => {

    var { searchkey } = req.query;

    var filepath = path.join(__dirname, '../json/goods.json');
    var arr = fs.readFileSync(filepath);
    arr = arr.toString() ? JSON.parse(arr) : []


    var newarr = arr.filter((item) => {
        return new RegExp(searchkey).test(item.name)
    })

    res.send({ code: 200, msg: '查询成功!', list: newarr })
})

// 删除接口
userRouter.post('/delete', (req, res) => {
    var { name } = req.body;

    var filepath = path.join(__dirname, '../json/goods.json');
    var arr = fs.readFileSync(filepath);
    arr = arr.toString() ? JSON.parse(arr) : []

    var a = arr.findIndex((item) => {
        return item.name == name;
    })

    if (a != 1) {
        arr.splice(a, 1);
        fs.writeFileSync(filepath, JSON.stringify(arr), 'utf-8')

        var newarr = arr.slice(0, 2);

        res.send({ code: 200, msg: '删除成功!', list: newarr })
    } else {
        res.send({ code: 400, msg: '删除失败!' })
    }
})

module.exports = userRouter;